﻿
/***
  ***author: hehuan
  ***date: 20180504
  ***mail: hehuan@ppdai.com
***/
var COMMONJS = {
  getQueryString:function(name){
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return decodeURIComponent(r[2]);
    return null;
  },
  //神策埋点 初始化
  countDate:function(){
    /*
    **判断是否在app内、
    **appVersion inv_app(在) other(不在)
    */
    var appVersion = "other";
    if(navigator.userAgent.indexOf("appVersion") != -1){
      appVersion = "inv_app";
    }else{
      appVersion = "other";
    }
    // 神策埋点
    (function(para){
        var p = para.sdk_url, n = para.name, w = window, d = document, s = 'script',x = null,y = null;
        w['sensorsDataAnalytic201505'] = n;
        w[n] = w[n] || function(a) {return function() {(w[n]._q = w[n]._q || []).push([a, arguments]);}};
        var ifs = ['track','quick','register','registerPage','registerOnce','clearAllRegister','trackSignup', 'trackAbtest', 'setProfile','setOnceProfile','appendProfile', 'incrementProfile', 'deleteProfile', 'unsetProfile', 'identify','login','logout','trackLink','clearAllRegister'];
        for (var i = 0; i < ifs.length; i++) {
          w[n][ifs[i]] = w[n].call(null, ifs[i]);
        }
        if (!w[n]._t) {
          x = d.createElement(s), y = d.getElementsByTagName(s)[0];
          x.async = 1;
          x.src = p;
          y.parentNode.insertBefore(x, y);
          w[n].para = para;
        }
      })({
        sdk_url: 'https://ac.ppdaicdn.com/js/sensorsdata.min.js',
        name: 'sa',
        server_url:'https://sensorsdata.ppdai.com/sa/?project=production'
      });
      sa.registerPage({
          product: appVersion, // 产品线名称，对应各个产品线，借款app对应loan_app,没有则传other
          platform: 'H5', // 平台类型H5
          product_h5: 'act_h5',  //区分不同的业务线  （方便后台看数据）
          h5_channel: this.getQueryString('regsourceid')?this.getQueryString('regsourceid'):'', // h5页面来源渠道，如果h5是app内部打开就传空字符串
          user_agent: window.navigator.userAgent, // http头中的useragent字段
          source: this.getQueryString("source")?this.getQueryString('source'):''
      });
      sa.quick('autoTrack');
  },
  // 神策埋点 按钮点击事件统计
  saTrackBtn:function(parText,parTargetUrl){
    sa.track('h5_clk', {
        tgt_type: 'button',
        tgt_name: 'h5-ACT-' + parText,
        tgt_event_id: 'h5_ACT_button',
        target_url: parTargetUrl,
        url: location.href
    });
	},
  //获取用户username
  getUserName(userName){
    if(userName){
      sa.login(userName);
    }
  },
  // 打开弹窗
  openPopup:function(index){
		$('.bg,.popup'+index).show();
	},
  // 关闭弹窗
	closePopup:function(index){
		$('.bg,.popup'+index).hide();
	},
  // 显示toast
  showToast:function(str){
		var _html = "<div id='toast'>"+str+"</div>";
		$(_html).appendTo($('body'));
    $('#toast').fadeIn();
		window.setTimeout(function(){
			var $toast = $('#toast');
      $toast.fadeOut(1000,function(){
        $toast.remove();
      });
		},1000);
	},
  // 数据请求
  getData:function(url,data,callback){
    var self = this;
    $.ajax({
      type:'post',
      url:url,
      data:data,
      async:false,
      cache:false,
      dataType:'json',
      xhrFields: {
        withCredentials: true
      },
      beforeSend:function(){
          self.showLoading();
      },
      complete:function(){
          self.closeLoading();
      },
      success:callback,
      error: function(){
  			self.closeLoading();
        alert('网络错误，请稍后重试！');
      }
    })
  },
  // loading
  showLoading:function(){
    var _html = ('<div class="loading">\
                  <img src="//oper.ppdaicdn.com/act/common/images/loading.gif" width="40" height="40">\
                </div>');
	    $(_html).appendTo($('body'))
  },
  // close loading
  closeLoading:function(){
    var $load = $('.loading');
    if ($load.length) {
        $load.remove();
    }
	},
  // 获取cookie
  getCookie:function(name){
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null){
        return unescape(arr[2]);
    }else{
        return null;
    }
  },
  // 判断是否app
  isAppVersion:function(){
    if(navigator.userAgent.indexOf("appVersion") != -1){
      return true;
    }else{
      return false;
    }
  },
  // 理财APP分享
  lendShare:function(obj){
    ppd.ready(function(){
      ppd.call('jfShare',{
        imgData: obj.imgData, //base64编码
        imgURL: obj.imgURL, // 分享左侧图片链接地址
        title: obj.title, //分享标题
        desc: obj.desc, //分享窗口简要介绍
        linkURL: obj.linkURL, //分享窗口的链接地址
        type: obj.type, // 1,2,3 1=>登陆 2=>注册 3=>不需要判断登陆状态 //默认值3
        remark: obj.remark, //备注 额外需要添加的参数等
        extendParams: obj.extendParams,
        platforms: obj.platforms, // [5, 4, 2, 1, 3, 0, 6], //分享渠道  0=>sina,1=>QQ空间,2=>QQ,3=>QQ微博,4=>微信好友，5=>微信朋友圈,6=>复制链接,7 ...
        callback: obj.callback, //true或false
        newcallback: obj.newcallback, // 0=>不需要任何操作 , 1=>回调js, 2=>回调esb接口
        // jsFunctionName:shareSuccess('测试分享成功后回调'),
        parms: {
          "aid": 24
        }, // callback为ture  回调参数（必填）接口的参数
        interfaceName: obj.interfaceName, //接口地址  如果此接口不需要参数 parameter 为空
        shareType:obj.shareType,//0表示非海报分享  1表示海报分享
        ppdDays:obj.ppdDays,//在拍拍贷多少天
        posters:obj.posters,//海报链接地址
        success: function(res) {
        },
        cancel: function(res) {
          alert('取消');
        }
      })
    })
  },
  // 理财APP原生标题栏
  titleBar:function(isHideBr,title,rightTxt,bounces){
    ppd.ready(function(){
      ppd.call('jfTitleBar', {
        visible:isHideBr, //控制整个标题栏是否可见，默认为1可见
        titlename:title,//控制整个标题名称
        rightbtn:{
          visible:1, //是否显示, 默认为1显示
          content:"",
          onclick:'ppdLender.jfShare()'
        },
        bounces: bounces, // 1:支持弹簧效果, 0:表示不支持
        success: function (res) {
        }
      })
    })
  },
  // 登录
  login:function(){
		var self = this;
    if(navigator.userAgent.indexOf("appVersion") == -1){
	var params=window.location.href.replace(/#\//g,'')
      window.location.href = 'https://ac.ppdai.com/?redirect=' +params;
      //window.location.href = 'https://ac.ppdai.com/?redirect=' + encodeURIComponent(window.location.href);
      return false;
    }
		ppd.ready(function(){
			if(!self.getCookie("token") ){
		     //登录hybrid
				ppd.call('jfLogin', {
					success: function (res) {
							 //客户端登录成功
						 ppd.call('jfRefreshH5', {
								refreshUrl:window.location.href,
								success: function (res) {
								},
								fail: function (res) {
									alert('客户端未登录');
								}
						 });
					 },
					 cancel: function (res) {
						 ppd.call('jfCloseWin');
					 }
				});
			}
		});
	},
  //跳回原生首页
  jumpHome:function(){
    ppd.ready(function(){
      ppd.call('jfCloseWin');
    })
  },
  // 打开原生页面
  openWindow:function(value){
    ppd.call('jfOpenWin', {
      url:value
    });
  },
  //微信分享配置公共方法
  WeiXinShare:function(shareOption,callback){
    $.ajax({
      url:'//wechat.ppdai.com/jssdk/init?url='+encodeURIComponent(window.location.href),
      type:'get',
      dataType:'json',
      data:{},
      success:function (data) {
          wx.config({
              debug: false,
              appId:data.content.appId,
              timestamp: data.content.timestamp,
              nonceStr: data.content.nonceStr,
              signature: data.content.signature,
              jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
          });
          if(!shareOption){
            shareOption = {
                title: '拍拍贷',
                desc: '拍拍贷',
                linkUrl: window.location.href,
                imgUrl: '../images/share.png'
            }
          }
          if(!callback){
            callback = function(){}
          }
          wx.ready(function () {
              /*分享到朋友圈*/
              wx.onMenuShareTimeline({
                  title: shareOption.title,
                  link: shareOption.linkUrl,
                  imgUrl: shareOption.imgUrl,
                  success: callback,
                  cancel: function () { }
              });

              /*分享给朋友*/
              wx.onMenuShareAppMessage({
                  title: shareOption.title,
                  desc: shareOption.desc,
                  link: shareOption.linkUrl,
                  imgUrl: shareOption.imgUrl,
                  success: callback,
                  cancel: function () { }
              });

              /*分享到QQ*/
              wx.onMenuShareQQ({
                  title: shareOption.title,
                  desc: shareOption.desc,
                  link: shareOption.linkUrl,
                  imgUrl: shareOption.imgUrl,
                  success: callback,
                  cancel: function () { }
              });

              /*分享到腾讯微博*/
              wx.onMenuShareWeibo({
                  title: shareOption.title,
                  desc: shareOption.desc,
                  link: shareOption.linkUrl,
                  imgUrl: shareOption.imgUrl,
                  success: callback,
                  cancel: function () { }
              });

              /*分享到QQ空间*/
              wx.onMenuShareQZone({
                  title: shareOption.title,
                  desc: shareOption.desc,
                  link: shareOption.linkUrl,
                  imgUrl: shareOption.imgUrl,
                  success: callback,
                  cancel: function () { }
              });
          });
      },
      error:function () {
          //alert('网络错误');
      }
    });
  }
}
